<?php

class CController extends CBase {
	
	/**
	 * 控制器
	 * @var string
	 */
	protected $_controller;
	
	/**
	 * 动作
	 * @var string
	 */
	protected $_action;
	
	private $_renderParam=array();
	
	protected $_smarty = null;
	
	function __construct($controller, $action){
		parent::__construct();
		
		$this->_controller = $controller;
		$this->_action = $action;
	}
	
	function __get($name)
	{
		if("formValidator"===$name)
		{
			if(!$this->_validator)
			{
				$this->_validator = new CValidatorManage();
			}
			
			return $this->_validator;
		}
	}

	protected function render($viewFile, $param=array())
	{
		$this->_renderParam = array_merge($param,$this->_renderParam);
		
		$viewSet = Config::get("viewSet");
		
		$viewDir = $viewSet["viewDir"];
		
		$viewDir = $this->getAbsolutePath($viewDir);

		$viewFile .= $viewSet["ext"];
		
		$smarty = $viewSet["smarty"];
		
		$this->generateFrameworkJs();
		
		$viewObj = null;
		
		if($smarty)
		{
			$smartyOpen = $smarty["open"];
			
			if($smartyOpen)
			{
				$viewObj = new CViewSmarty();
			}
		}
		
		if(!$viewObj)
		{
			$viewObj = new CView();
		}

		$viewObj->render($viewDir,$viewFile,$this->_renderParam);

		//CView::render($viewDir,$viewFile,$this->_renderParam);
	}
	
	protected function setViewParam($k,$v,$overWrite=false)
	{
		if($overWrite || !key_exists($k, $this->_renderParam))
		{
			$this->_renderParam[$k] = $v;
		}
	}
	
	/**
	 * 根据键获取提交的数据值，可以设置Html和sql转义
	 * @param $key 键
	 * @param $method post,get,request之一 ,默认post
	 * @param $default 不存在时取该默认值
	 * @param $htmlspecialchars 是否html转义，默认转义
	 * @param $sqlspecialchars 是否sql转义，默认转义
	 */
	protected function getRequestData($key,$method="POST",$default="",$htmlspecialchars=true,$sqlspecialchars=true)
	{
		$value=null;
		$method = strtoupper($method);
		switch ($method)
		{
			case "GET":
				$value = isset($_GET[$key])?$_GET[$key]:$default;
				break;
			case "POST":
				$value = isset($_POST[$key])?$_POST[$key]:$default;
				break;
			case "REQUEST":
				$value = isset($_REQUEST[$key])?$_REQUEST[$key]:$default;
				break;
		}
		
		if($htmlspecialchars)
		{
			if(is_array($value))
			{
				$value = array_map("htmlspecialchars",$value);
			}
			else
			{
				$value = htmlspecialchars($value);
			}
		}
		
		if($sqlspecialchars)
		{
			if(!get_magic_quotes_gpc())
			{
				if(is_array($value))
				{
					$value = array_map("addslashes",$value);
				}
				else
				{
					$value = addslashes($value);
				}
			}
		}
		
		return $value;
	}
	
	private function generateFrameworkJs()
	{
		if($this->_validator)
		{
			$validatorJs = $this->_validator->getValidatorJsFile();
			if($validatorJs)
			{
				$this->_renderParam["frameworkJs"] = "<script src='".Config::get("formValidator.jsUrl","/").$validatorJs."'></script>";
			}
		}
	}
	
	
}

?>